package com.hngy.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.hngy.common.CustomException;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author LiKe
 * @date 2021/12/30 14:12
 */
public class ALiYunOSSUtils {
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    private static final String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    private static final String accessKeyId = "LTAI5t9Vm8G8uMS2BAsFfP8k";
    private static final String accessKeySecret = "lTEjLAmE6iGx9wQGfB8sdsCkIW3iwa";
    private static final String bucketName = "reggie-img";
    //private static final String objectName = "exampledir/exampleobject.txt";

    public static void upload(InputStream inputStream,String objectName){

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            ossClient.putObject(bucketName, "img/"+objectName, inputStream);

        } catch (Exception e){
            throw new CustomException("上传失败！");

        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

    }

    public static InputStream download(String objectName){

        OSS ossClient = null;
        InputStream content = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。

            OSSObject ossObject = ossClient.getObject(bucketName, "img/"+objectName);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            content = ossObject.getObjectContent();


            /*if (content != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) break;
                    System.out.println("\n" + line);
                }
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                content.close();
            }*/
        } catch (Exception e){
            e.printStackTrace();
        }  finally {
            // 关闭OSSClient。
            //ossClient.shutdown();
        }
        return content;

    }

}
